package com.example.yls.demoa;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {
    private Button starServ;
    private Button stopServ;
    private Button bind;
    private Button unbind;
    private ServiceConnection serviceConnection;
    private MyBinder binder;
    private  Button stnAdd;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        serviceConnection=new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
                Log.e("MainActivity","onServiceConnected");
                binder=(MyBinder)iBinder;
            }

            @Override
            public void onServiceDisconnected(ComponentName componentName) {
                Log.e("MainActivity","onServiceDisconnected");
            }
        };

        starServ=findViewById(R.id.start_service);
        stopServ=findViewById(R.id.stop_service);


        bind=findViewById(R.id.bind_service);
        unbind=findViewById(R.id.unbind_service);

        starServ.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent();
                intent.setClass(MainActivity.this,MyService.class);
                startService(intent);

            }
        });
        stopServ.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent();
                intent.setClass(MainActivity.this,MyService.class);
                stopService(intent);

            }
        });
        stnAdd =findViewById(R.id.stn_add);
        stnAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int result=binder.add(100,200);
                Log.e("binder.add","result"+result);
            }
        });


        bind.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent();
                intent.setClass(MainActivity.this,MyService.class);
                bindService(intent,serviceConnection,BIND_AUTO_CREATE);

            }
        });
        unbind.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                unbindService(serviceConnection);
            }
        });
    }
}
